#include "SayCommand.h"

#include "../../../Memory/GameData.h"
#include "../../../SDK/CPacket.h"

inline constexpr std::u8string string_replace(std::u8string s, const std::u8string_view findS, const std::u8string_view replaceS) {
	for (size_t i{};;) {
		i = s.find(findS, i);
		if (i != std::string::npos)
			s.replace(i, findS.length(), replaceS);
		else
			return s;
	}
}

inline constexpr std::u8string parse(std::u8string s) {
	constexpr std::array<std::pair<std::u8string_view, std::u8string_view>, 7> patterns{// 有个问题 \\n
																						std::pair{u8"\\\\", std::u8string_view{u8"\\\0", 2}},
																						std::pair{u8"\\n", u8"\n"},
																						std::pair{u8"\\r", u8"\r"},
																						std::pair{u8"\\t", u8"\t"},
																						std::pair{u8"\\f", u8"\f"},
																						std::pair{u8"\\\"", u8"\""},
																						std::pair{std::u8string_view{u8"\\\0", 2}, u8"\\"}};

	for (const auto& p : patterns)
		s = string_replace(s, p.first, p.second);
	return s;
}

bool SayCommand_onExecute(const fast_io::vector<std::u8string>& args) {
	if (args.size() < 2)
		return false;
	std::u8string os{};
	for (size_t i = 1; i < args.size(); i++) {
		if (i > 1) [[likely]]
			os.push_back(u8' ');
		os.append(args[i]);
	}
	const auto localplayer = g_Data.getLocalPlayer();
	C_TextPacket_view textPacket{localplayer->getNameTag()->getText(), fast_io::u8concat(localplayer->getUserId())};
	textPacket.message.setText(parse(os));
	g_Data.getClientInstance()->loopbackPacketSender->sendToServer(&textPacket);
	return true;
}

ICommand SayCommand{
	u8"say",
	u8".say <message>",
	{u8"Sends a chat message", u8"发送聊天信息", u8"發送聊天資訊", u8"チャットメッセージを送信"},
	{},
	fast_io::vector<aliasList_struct>{},  // If empty must use fast_io::vector<aliasList_struct>{}
	nullptr,
	&SayCommand_onExecute};